<?php
namespace Rainrock\Framework\Chajian;

/**
	上传文件类upfileChajian
	create：chenxihu
	createdt：2013-11-15
	explain：上传文件类，可上传任何文件类型
*/

use Rainrock\Framework\kernel\core\Chajian;
use Rainrock\Framework\kernel\base\Rock;

class upfileChajian extends Chajian{
	
	public $uptype;     //上传类型
	public $maxsize; //上传大小(MB)
	public $path;    //文件夹
	
	private $thumbnail		= '150x150';
	private $shuiyin		= '';
	private $compress		= '';
	private $rootsave		= false; //特殊文件是否根目录保存默认不需要
	
	private $jpgallext		= '|jpg|png|gif|bmp|jpeg|';	//图片格式
	
	
	/**
	*	初始化
	*	@param	$uptype string 上传类型
	*	@param	$path string 上传目录 如：upload|e|ee
	*	@param	$maxsize ing 上传大小(MB)
	*/
	public function initUpfile($uptype,$path,$maxsize=0)
	{
		if($uptype=='image')$uptype = $this->jpgallext;
		$this->uptype	= str_replace('|',',', $uptype);
		$this->maxsize	= $maxsize;
		$this->path		= $path;
		return $this;
	}
	
	/**
	*	设置缩略图大
	*/
	public function setThumbnail($val)
	{
		$this->thumbnail = $val;
		return $this;
	}
	

	public function setRootsave($val)
	{
		$this->rootsave = $val;
		return $this;
	}
	
	/**
	*	压缩
	*/
	public function setCompress($val)
	{
		$this->compress = $val;
		return $this;
	}
	
	/**
	*	设置是否水印
	*/
	public function setShuiyin($val)
	{
		$this->shuiyin = $val;
		return $this;
	}
	
	private function _getmaxupsize($lx)
	{
		$iniMax = strtolower(ini_get($lx));
        if ('' === $iniMax) {
            return PHP_INT_MAX;
        }
        $max = ltrim($iniMax, '+');
        if (0 === strpos($max, '0x')) {
            $max = intval($max, 16);
        } elseif (0 === strpos($max, '0')) {
            $max = intval($max, 8);
        } else {
            $max = (int) $max;
        }
        switch (substr($iniMax, -1)) {
            case 't': $max *= 1024;
            case 'g': $max *= 1024;
            case 'm': $max *= 1024;
            case 'k': $max *= 1024;
        }
        return $max;
	}
	
	/**
	*	获取可最大上传的(字节)
	*/
	public function getmaxupsize()
	{
		$post = $this->_getmaxupsize('post_max_size');
		$upmx = $this->_getmaxupsize('upload_max_filesize');
		if($post < $upmx)$upmx = $post;
		return $upmx;
	}
	
	/**
	*	获取可最大上传的(M)
	*/
	public function getmaxzhao()
	{
		$size = $this->getmaxupsize();
		$size = $size / 1024 / 1024;
		return (int)$size;
	}
	

	/**
	*	是否图片
	*/
	public function isimg($ext)
	{
		return $this->contain($this->jpgallext, '|'.$ext.'|');
	}
	
	/**
	*	判断是不是图片
	*/
	public function isimgsave($ext, $file)
	{
		$fileobj	= getimagesize($file);
		if(!$fileobj){
			@unlink($file);
			return false;
		}
		$picw	= $fileobj[0];
		$pich	= $fileobj[1];
		$mime	= strtolower($fileobj['mime']);
		
		if($this->contain($mime,'bmp'))$ext = 'bmp';
		if($mime=='image/gif')$ext = 'gif';
		if($mime=='image/png')$ext = 'png';
		
		$arr[0] = $picw;
		$arr[1] = $pich;
		$arr[2] = $ext;
		$arr[3] = $mime;
		return $arr;
	}
	
	/**
	*	内容上传
	*/
	public function createImage($cont, $ext, $filename)
	{
		$save_path			= $this->ismulu($this->path);
		if(!$save_path)return '无效目录';
		
		$randname	 		= $this->getrandfile(1, '');
		$file_newname		= ''.$randname.'.'.$ext.'';
		$allfilename		= ''.$save_path.'/'.$file_newname.'';
		
		$bo 	= Rock::createFile($allfilename, $cont, ROOT_PATH);
		if(!$bo)return '无法写入文件夹';
		
		$narr = $this->imageChuli($allfilename, $ext);
		if($narr && is_string($narr))return $narr;
		
		$fileext   = $narr['fileext'];
		
		$barr 	= array(
			'newfilename' => $file_newname,
			'oldfilename' => $filename.'.'.$fileext,
			'filetype'    => '',
			'filepath'    => '',
			'fileext'     => $fileext,
			'allfilename' => $allfilename,
			'thumbpath'   => '',
			'isimg'       => false,
			'picw'        => 0,
			'pich'        => 0
		);
		foreach($narr as $k=>$v)$barr[$k] = $v;
		return $barr;
	}
	
	/**
	*	目录判断
	*/
	public function ismulu($path)
	{
		$updir = $path;
		$updir = str_replace(array(' ','.'),'', trim($updir));
		$updir = str_replace(array('{month}','month'),date('Y-m'), $updir);
		$updir = str_replace(array('{Year}','Year'),date('Y'), $updir);
		$updir = str_replace(array('{','}'),'', $updir);
		$updir = str_replace(',','|', $updir);
		$bobg  = preg_replace("/[a-zA-Z0-9_]/",'', $updir);
		$bobg  = str_replace(array('-','|','/',':'),'', $bobg);
		if($bobg)return '';
		$updir = str_replace('|', '/', $updir);
		return $updir;
	}
	
	
	/**
	*	上传
	*	@param	$name	string	对应文本框名称
	*	@param	$cfile	string	文件名心的文件名，不带扩展名的
	*	@return	string/array
	*/
	public function up($name='file',$cfile='')
	{
		if(!$_FILES)return 'sorry!';
		$this->path		= $this->ismulu($this->path);
		if(!$this->path)return '无效目录';
		$file_name		= $_FILES[$name]['name'];
		$file_size		= $_FILES[$name]['size'];//字节
		$file_type		= $_FILES[$name]['type'];
		$file_error		= $_FILES[$name]['error'];
		$file_tmp_name	= $_FILES[$name]['tmp_name'];
		$zongmax		= $this->getmaxupsize();	
		if($file_size<=0 || $file_size > $zongmax){
			return '文件为0字节/超过'.$this->formatsize($zongmax).'，不能上传';
		}
		$file_sizecn	= $this->formatsize($file_size);
		$file_ext		= $this->getext($file_name);//文件扩展名
		
		if(!$this->isempt($this->uptype) && !$this->contain(','.$this->uptype.',', ','.$file_ext.',') && $this->uptype != '*'){
			return '禁止上传文件类型['.$file_ext.']';
		}

		$file_img		= $this->isimg($file_ext);
		if($file_error>0){
			$rrs = $this->geterrmsg($file_error);
			return $rrs;
		}
		
		if($this->maxsize>0 && $file_size>$this->maxsize*1024*1024){
			return '上传文件过大，限制在：'.$this->formatsize($this->maxsize*1024*1024).'内，当前文件大小是：'.$file_sizecn.'';
		}
		
		if(!$file_img && !$this->rootsave)$this->path = ''.ROOT_PACK.'/'.$this->path.''; //不是图片就存其他目录不存根目录
		
		$zpath = explode('/',$this->path);
		$mkdir = '';
		for($i = 0;$i<count($zpath);$i++){
			$mkdir.=''.$zpath[$i].'/';
			if(!is_dir($mkdir))mkdir($mkdir);
		}
		
		//新的文件名
		$file_newname	= $file_name;
		$randname		= $file_name;
		if(!$cfile==''){
			$file_newname=''.$cfile.'.'.$file_ext.'';
		}else{
			$randname	 = $this->getrandfile(1, '');
			$file_newname=''.$randname.'.'.$file_ext.'';
		}
		$save_path	= $this->path;
		

		$allfilename= $save_path.'/'.$file_newname.'';
		$upbool		= @move_uploaded_file($file_tmp_name,$allfilename);
		$thumbpath	= '';
		
		if(!$upbool)return '上传失败：'.$this->geterrmsg($file_error).'';
	
		$narr = $this->imageChuli($allfilename, $file_ext);
		if($narr && is_string($narr))return $narr;
		$barr = array(
			'newfilename' => $file_newname,
			'oldfilename' => $file_name,
			'filesize'    => $file_size,
			'filesizecn'  => $file_sizecn,
			'filetype'    => $file_type,
			'filepath'    => $save_path,
			'fileext'     => $file_ext,
			'allfilename' => $allfilename,
			'thumbpath'   => $thumbpath,
			'isimg'       => false,
			'picw'        => 0,
			'pich'        => 0
		);
		foreach($narr as $k=>$v)$barr[$k] = $v;
		return $barr;
	}
	
	private function imageChuli($allfilename, $file_ext)
	{
		$picw=0;$pich=0;
		$file_img	= $this->isimg($file_ext);
		if(!$file_img)return array();
		
		$fobj = $this->isimgsave($file_ext, $allfilename);
		if(!$fobj)return 'error:非法图片文件';
		
		$picw 		= $fobj[0];
		$pich 		= $fobj[1];
		$file_ext 	= $fobj[2];
		$filetype 	= $fobj[3];
		$imgobj		= $this->c('image');
		$filesize	= filesize($allfilename);
		
		//压缩
		if($this->compress && ($file_ext=='jpg' || $file_ext=='jpeg')){
			$sttuc	= explode('x', $this->compress);
			$yw 	= (int)$sttuc[0];
			$yh 	= (int)$this->arrvalue($sttuc, 1, 0);
			if($picw > $yw || $pich > $yh){
				$imgobj->createimg($allfilename);
				$yspaht = $imgobj->compress($yw, $yh);
				if($yspaht && file_exists($yspaht)){
					if($allfilename != $yspaht)@unlink($allfilename);
					$allfilename 		= $yspaht;
					$filesize 			= filesize($yspaht);
					list($picw,$pich)	= getimagesize($yspaht);
				}
			}
		}
					
		//生成缩略图
		$sttua		= explode('x', $this->thumbnail);
		$lw 		= (int)$sttua[0];
		$lh 		= (int)$sttua[1];
		
		if($picw>$lw || $pich>$lh){
			$imgobj->createimg($allfilename);
			$thumbpath 	= $imgobj->thumbnail($lw, $lh, 1);
		}else{
			$thumbpath	= $allfilename;
		}
		
		$filesizecn = $this->formatsize($filesize);
		if($this->shuiyin=='size'){
			$imgobj->createimg($thumbpath);
			$imgobj->addwater($filesizecn);
		}
		
		return array(
			'allfilename' 	=> $allfilename,
			'thumbpath' 	=> $thumbpath,
			'picw' 			=> $picw,
			'pich' 			=> $pich,
			'fileext' 		=> $file_ext,
			'filesize' 		=> $filesize,
			'filetype' 		=> $filetype,
			'filesizecn' 	=> $filesizecn,
			'isimg' 		=> true
		);
	}
	
	private function getrandfile($xu, $val)
	{
		$randname	= ''.date('d_His').''.rand(10,99*$xu).'';
		if($val==$randname)return $this->getrandfile($xu+1, $val);
		return $randname;
	}
	
	private function geterrmsg($code)
	{
		$arrs[1] = '上传文件大小超过服务器允许上传的最大值';
		$arrs[2] = '上传文件大小超过HTML表单中隐藏域MAX_FILE_SIZE选项指定的值';
		$arrs[6] = '没有找不到临时文件夹';
		$arrs[7] = '文件写入失败';
		$arrs[8] = 'php文件上传扩展没有打开';
		$arrs[3] = '文件只有部分被上传';
		$rrs 	 = '上传失败，可能是服务器内部出错，请重试';
		if(isset($arrs[$code]))$rrs=$arrs[$code];
		return $rrs;
	}
	
	//返回文件大小
	public function formatsize($size)
	{
		return Rock::formatsize($size);
	}
	
	//获取扩展名
	public function getext($file)
	{
		return strtolower($this->getexts($file));
	}
	
	//获取扩展名
	public function getexts($file)
	{
		return substr($file,strrpos($file,'.')+1);
	}
}
